import 'package:ant_icons/ant_icons.dart';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter_color/flutter_color.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_vant_kit/main.dart';
import 'package:flutter_web_2021/Include.dart';
import 'package:flutter_web_2021/entity/CommoditySortEntity.dart';
import 'package:flutter_web_2021/pages/mmx/home/publish_works/GiveBackProductsPage.dart';
import 'package:flutter_web_2021/pages/mmx/home/publish_works/ProductDetailsPage.dart';
import 'package:flutter_web_2021/pages/mmx/home/publish_works/mall/SearchPage.dart';
import 'package:flutter_web_2021/utils/toast/OkToastUtil.dart';
import 'package:flutter_web_2021/widgets/img/ImagesViews.dart';

class MallPage extends BasePage {
  static String dartPath = "lib/pages/mmx/home/publish_works/mall/MallPage.dart";

  @override
  _MallPageState createState() => _MallPageState();

  @override
  String get pageName => '商城';
}

class _MallPageState extends BasePageState<MallPage> with WidgetsBindingObserver {
  FocusNode focusNode = FocusNode();
  bool keyboardPopUp = false;

  String searchContent = "";

  List<CommoditySortEntity> commoditySortEntitys = [
    CommoditySortEntity(id: "0", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "手机"),
    CommoditySortEntity(id: "1", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "电脑"),
    CommoditySortEntity(id: "2", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "数码"),
    CommoditySortEntity(id: "3", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "家电"),
    CommoditySortEntity(id: "4", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "家居"),
    CommoditySortEntity(id: "5", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "服饰"),
    CommoditySortEntity(id: "6", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "美妆"),
    CommoditySortEntity(id: "7", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "水果"),
    CommoditySortEntity(id: "8", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "生鲜"),
    CommoditySortEntity(id: "9", imgUri: "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", title: "超市"),
  ];
  List<List<CommoditySortEntity>> slelist = new List();

  dynamic options = [
    PickerItem("100-150朵"),
    PickerItem("200-250朵"),
    PickerItem("300-350朵"),
    PickerItem("400-450朵"),
    PickerItem("500-550朵"),
    PickerItem("600-650朵"),
  ];

  List productList = [
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
    {"id": "0", "imgUri": "https://t7.baidu.com/it/u=801209673,1770377204&fm=193&f=GIF", "title": "超市", "bloom": "800朵花"},
  ];
  List tabData = [
    {"id": "11", "title": '手机'},
    {"id": "12", "title": '数码产品'},
    {"id": "13", "title": '美妆'},
    {"id": "13", "title": '笔记本'},
    {"id": "13", "title": '家居'},
    {"id": "13", "title": '休闲零食'},
  ];

  @override
  void didChangeMetrics() {
    super.didChangeDependencies();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (MediaQuery.of(context).viewInsets.bottom == 0) {
        //关闭键盘
        keyboardPopUp = false;
        focusNode.unfocus();
      } else {
        //显示键盘
        keyboardPopUp = true;
      }
    });
  }

  @override
  void initState() {
    super.initState();
    //初始化
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    //销毁
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

// 监听返回
  Future<bool> _requestPop() {
    if (keyboardPopUp) {
      focusNode.unfocus();
    } else {
      Navigator.of(context).pop();
    }
    return new Future.value(false);
  }

  ///轮播图
  Widget swiper() => Container(
        height: 150,
        padding: Dimens.edgeInsets_lr_dp15,
        child: Swiper(
          itemBuilder: (BuildContext context, int index) {
            return Container(
              height: 150,
              child: ImagesViews.rectangle(
                "https://tse1-mm.cn.bing.net/th/id/R-C.d9522d356a538d12550bfc638abcba82?rik=5ctIvNjQV1q9bg&riu=http%3a%2f%2fimage2.sina.com.cn%2fent%2fy%2fp%2f2006-07-01%2fU1735P28T3D1143020F326DT20060701184010.jpg&ehk=vX%2fRQTI6nLFxuhrZxu0NUcLFYTpZpJZKKPgrn3bh38g%3d&risl=&pid=ImgRaw&r=0",
                borderRadius: 10.0,
              ),
            );
          },
          itemCount: 3,
          // pagination: new SwiperPagination(),
          control: new SwiperControl(iconPrevious: AntIcons.left_circle, iconNext: AntIcons.right_circle, color: Colours.color_gray_585858),
          loop: true,
          autoplay: true,
          autoplayDelay: 5000,
          duration: 1000,
        ),
      );

  ///商品分类
  Widget commoditySort() => Container(
        alignment: Alignment.center,
        height: 100,
        // padding: Dimens.edgeInsets_lr_dp15,
        child: Swiper(
          itemBuilder: (BuildContext context, int index1) => GridView.builder(
              shrinkWrap: true,
              physics: new NeverScrollableScrollPhysics(),
              itemCount: slelist[index1].length,
              // physics: new NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                // 一行几列
                crossAxisCount: 5,
                // 设置每子元素的大小（宽高比）
                childAspectRatio: 1,
                // 元素的左右的 距离
                crossAxisSpacing: 0,
                // 子元素上下的 距离
                mainAxisSpacing: 0,
              ),
              itemBuilder: (BuildContext context, int index2) {
                return Container(
                  child: InkWell(
                    onTap: () {
                      Log().info(slelist[index1][index2].title);
                      AppNavigator.push(context, GiveBackProductsPage());
                    },
                    child: Column(
                      children: [
                        Container(
                          height: 40,
                          width: 40,
                          child: ImagesViews.rectangle(
                            slelist[index1][index2].imgUri,
                            borderLine: 1,
                            borderColor: Colours.color_gray_585858,
                            borderRadius: 25.0,
                          ),
                        ),
                        Gaps.vGap4,
                        Text(
                          slelist[index1][index2].title,
                          style: TextStyles.btnText15_333333,
                        ),
                      ],
                    ),
                  ),
                );
              }),
          itemCount: slelist.length,
          pagination: SwiperPagination(
              builder: DotSwiperPaginationBuilder(
            color: Color.fromRGBO(0, 0, 0, .2),
            activeColor: Colours.color_orange_FF5800,
          )),
          scrollDirection: Axis.horizontal,
          autoplay: false,
          loop: false,
          // onTap: (index) => Log().info('Swiper pic $index click'),
        ),
      );

  @override
  Widget build(BuildContext context) {
    List<CommoditySortEntity> list = new List();
    slelist.clear();
    for (int i = 0; i < commoditySortEntitys.length; i++) {
      list.add(commoditySortEntitys[i]);
      if ((i + 1) % 5 == 0 && i != 0) {
        slelist.add(List<CommoditySortEntity>.generate(list.length, //要传入的长度，不能大于_categoryListModel.goods的长度，可根据实际需要设置
            (int index) {
          //创建新的QualitySamplingGoodsModel，默认系统会主动帮我们创建
          return list[index];
        }, growable: true));
        list.clear();
      }
    }
    if (list.length > 0) {
      slelist.add(List<CommoditySortEntity>.generate(list.length, //要传入的长度，不能大于_categoryListModel.goods的长度，可根据实际需要设置
          (int index) {
        //创建新的QualitySamplingGoodsModel，默认系统会主动帮我们创建
        return list[index];
      }, growable: true));
      list.clear();
    }

    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: MyAppBar.appBarSearch(context, "搜索商品", contentFocusNode: focusNode, onPressed: () {
        _requestPop();
      }, onSubmitted: (String text) {
        searchContent = text;
        search(searchContent);
      }),
      backgroundColor: Colours.color_black_252525,
      body: Container(
        decoration: BoxDecorations.rectCircle10,
        width: Dimens.screenWidth(),
        child: Stack(
          children: [
            ListView(
              children: [
                Gaps.vGap15,
                swiper(),
                Gaps.vGap15,
                commoditySort(),
                Dividers.dividerHorizontal(height: 10, color: HexColor('#F1F1F1')),
                Gaps.vGap20,
                Container(
                  padding: Dimens.edgeInsets_lr_dp15,
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Text(
                            "商品列表",
                            style: TextStyles.btnText15B_333333,
                          ),
                          Expanded(child: Gaps.hGap4),
                          Container(
                            padding: EdgeInsets.only(top: 1, bottom: 1, left: 8, right: 5),
                            decoration: BoxDecorations.rectCircleHollowGray_10,
                            child: InkWell(
                              child: Row(
                                children: [
                                  Text(
                                    "50-60朵花",
                                    style: TextStyles.btnText12_666666,
                                  ),
                                  Gaps.wGap2,
                                  Baseline(
                                    baseline: 15,
                                    baselineType: TextBaseline.alphabetic,
                                    child: Icon(
                                      AntIcons.caret_down,
                                      color: Colours.color_gray_666666,
                                      size: 14,
                                    ),
                                  ),
                                ],
                              ),
                              onTap: () {
                                showModalBottomSheet(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return Picker(
                                        colums: options,
                                        defaultIndex: 0,
                                        showToolbar: true,
                                        onConfirm: (values, index) {
                                          Log().info(values.toString() + ";" + index.toString());
                                          AppNavigator.pop(context);
                                        },
                                      );
                                    });
                              },
                            ),
                          ),
                          Gaps.wGap5,
                        ],
                      ),
                      Gaps.vGap18,
                      StaggeredGridView.countBuilder(
                        shrinkWrap: true,
                        physics: new NeverScrollableScrollPhysics(),
                        crossAxisCount: 4,
                        //横轴单元格数量
                        itemCount: productList.length,
                        //元素数量
                        itemBuilder: (context, i) {
                          return Card(
                            margin: EdgeInsets.all(0),
                            elevation: 2.0,
                            shape: new RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
                            child: InkWell(
                              onTap: () {
                                AppNavigator.push(context, ProductDetailsPage());
                              },
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Expanded(
                                      child: ImagesViews.customizeRectangle(
                                    productList[i]["imgUri"],
                                    borderRadius: 10.0,
                                  )),
                                  Gaps.vGap8,
                                  Padding(
                                    padding: Dimens.edgeInsets_lr_dp10,
                                    child: Text(
                                      productList[i]["title"],
                                      style: TextStyles.btnText13_333333,
                                    ),
                                  ),
                                  Gaps.vGap8,
                                  Padding(
                                    padding: Dimens.edgeInsets_lr_dp10,
                                    child: Text(
                                      productList[i]["bloom"],
                                      style: TextStyles.btnText11_F06F2A,
                                    ),
                                  ),
                                  Gaps.vGap8,
                                ],
                              ),
                            ),
                          );
                        },
                        staggeredTileBuilder: (index) {
                          return StaggeredTile.count(2, index.isEven ? 3 : 2.5); //第一个参数是横轴所占的单元数，第二个参数是主轴所占的单元数
                        },
                        padding: EdgeInsets.all(0),
                        mainAxisSpacing: 9.0,
                        crossAxisSpacing: 9.0,
                      )
                    ],
                  ),
                )
              ],
            ),
            Offstage(
              offstage: keyboardPopUp,
              child: Container(
                padding: Dimens.edgeInsets_lr_dp15,
                color: Colours.bg_while,
                child: Column(
                  children: [
                    Gaps.vGap15,
                    Row(
                      children: [
                        Expanded(
                            child: Text(
                          "搜索历史",
                          style: TextStyles.btnText15B_333333,
                        )),
                      ],
                    ),
                    Gaps.vGap15,
                    Container(
                      width: Dimens.screenWidth(),
                      child: Wrap(
                        spacing: 10,
                        runSpacing: 10,
                        children: tabData
                            .map((e) => Container(
                                  padding: EdgeInsets.only(left: 15, right: 15, top: 5, bottom: 5),
                                  decoration: BoxDecorations.rectCircle12,
                                  child: InkWell(
                                      onTap: () {
                                        focusNode.unfocus();
                                        search(e["title"]);
                                      },
                                      child: Baseline(
                                        baseline: 12,
                                        baselineType: TextBaseline.alphabetic,
                                        child: AutoSizeText(
                                          e["title"],
                                          style: TextStyles.btnTextWhile11,
                                        ),
                                      )),
                                ))
                            .toList(),
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  ///搜索
  search(text) {
    // ToastUtil.showToastBottom(text);
    AppNavigator.push(context, SearchPage(text));
  }
}
